﻿using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Validation;
using Drawing = DocumentFormat.OpenXml.Drawing;
using System;
using System.Drawing;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Packaging;
using System.Xml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using System.Net;
using DocumentFormat.OpenXml.Wordprocessing;
using NotesFor.HtmlToOpenXml;
using System.Collections;
using System.Text.RegularExpressions;

namespace OfficeDocumentsGenerator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {        
        private BackgroundWorker reportWorker;
        String originalFile = ".\\..\\..\\Templates\\Template.pptx";
        String destination = "";
        private int NoOfFiles = 0;        
        static uint id = 258;
        String documentFormat = "";

        public MainWindow()
        {
            InitializeComponent();
            
        }        

        private void showPopUp()
        {
            ProgressWindow pw = new ProgressWindow();
            pw.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            pw.ShowDialog();
        }

        private void generate_button_clicked(object sender, RoutedEventArgs e)
        {
            if (wordRadio.IsChecked == true)
            {
                documentFormat = "DOCX";
            }
            else if (xlsRadio.IsChecked == true)
            {
                documentFormat = "XLSX";
            }
            else if (pptRadio.IsChecked == true)
            {
                documentFormat = "PPTX";
            }
            else
            {
                MessageBox.Show("Please choose a file format"); 
                return; 
            }

            try
            {
                NoOfFiles = int.Parse(NumFiles.Text);
            }
            catch { MessageBox.Show("Please enter a valid number in file count"); return; }

            try 
            {
                destination = destPath.Text;
                if (!Directory.Exists(destination))
                {
                    MessageBox.Show("Specific output path '"+destination+"' doesn't exist");
                    return;
                }
            }
            catch { }

            reportWorker = new BackgroundWorker();
            reportWorker.WorkerReportsProgress = true;
            reportWorker.WorkerSupportsCancellation = true;
            reportWorker.DoWork += generateDocument;
            
            reportWorker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
            {
                int progress = args.ProgressPercentage;
                TestParent.ProgressPercentage = progress;
            };
            reportWorker.RunWorkerAsync();
            showPopUp();
        }

        private void generateDocument(object sender, DoWorkEventArgs e)
        {
            if (documentFormat == "DOCX") { generate_DOCX_Documents(); }
            else if (documentFormat == "XLSX") { generate_XLSX_Documents(); }
            else if (documentFormat == "PPTX") { generate_PPTX_Documents(); }
        }

        private void generate_DOCX_Documents()
        {            
            string[] filesArr = Directory.GetFiles(".\\..\\..\\Templates\\Images\\Graphs", "*.jpg");
            
            MyWebServer MWS = new MyWebServer();
            for (int i = 1; i <= NoOfFiles; i++)
            {
                Dictionary<string, string> htmlDictionary = new Dictionary<string, string>();
                string allLines = global::OfficeDocumentsGenerator.Properties.Resources.HTMLProperties;
                string[] lines = allLines.Split('\n');

                for (int j = 0; j < lines.Length; j++)
                {
                    string[] keyVal = lines[j].Split('$');
                    htmlDictionary.Add(keyVal[0], keyVal[1]);
                }

                string indexHtml = "";
                indexHtml += htmlDictionary["DOCTYPE"];
                indexHtml += htmlDictionary["htmlStart"];
                indexHtml += htmlDictionary["head"];
                indexHtml += htmlDictionary["bodyStart"];
                indexHtml += htmlDictionary["firstTable"];
                indexHtml += htmlDictionary["brandLogo"];
                indexHtml += htmlDictionary["perfTestHeader"];
                indexHtml += htmlDictionary["projectNameHeader"];
                indexHtml += htmlDictionary["version"];

                string dateHeader = htmlDictionary["dateHeader"];
                dateHeader = dateHeader.Replace("10-Sep-2012", DateTime.Now.ToShortDateString());
                indexHtml += dateHeader;

                indexHtml += htmlDictionary["firstTableEnd"];
                indexHtml += htmlDictionary["br1"];

                String div1 = htmlDictionary["div1"];
                div1 = div1.Replace("10-Sep-2012", DateTime.Now.ToShortDateString());
                indexHtml += div1;

                indexHtml += htmlDictionary["br2"];
                indexHtml += htmlDictionary["toc"];
                indexHtml += htmlDictionary["br3"];
                indexHtml += htmlDictionary["executiveSummary"];
                indexHtml += htmlDictionary["purpose"];
                indexHtml += htmlDictionary["objective"];
                indexHtml += htmlDictionary["overView"];
                //add random text from contentTextFile - start

                string[] readText = File.ReadAllLines(".\\..\\..\\Templates\\ContentTextFile.txt");
                Random _r = new Random();

                for (int k = 0; k < 1; k++)
                {
                    int n = _r.Next(readText.Length - 1);
                    indexHtml += "<h3>" + readText[n] + "</h3>";
                }


                //add random text from contentTextFile - end
                indexHtml += htmlDictionary["br4"];
                indexHtml += htmlDictionary["testEnvironment"];
                indexHtml += htmlDictionary["targetServers"];

                //String[] envArr = TestParent.strtextAreaEnv.Split('\n');

                //for (int i = 0, j = 1; i < envArr.Length; i++)
                //{
                //    if (envArr[i] != "")
                //    {
                //        indexHtml += "<li> <b>" + j + ")</b> " + envArr[i] + "</li>";
                //        j++;
                //    }
                //}
                //indexHtml += "</p><br><br><br>";
                indexHtml += htmlDictionary["deploymentDiagramText"];
                indexHtml += htmlDictionary["deploymentDiagramImg"];
                indexHtml += "<br><br><br><br>";
                indexHtml += htmlDictionary["loadgenerators"];
                indexHtml += htmlDictionary["testResults"];

                indexHtml += htmlDictionary["testResultsStart"];

                //append test run summary start

                indexHtml += htmlDictionary["resultSummaryTableHeader"];
                //Dictionary<String, String> Dict = (Dictionary<String, String>)TestParent.TestRunInformationArrayList[0];
                String table = "";
                //foreach (KeyValuePair<String, String> entry in Dict)
                //{
                //    if (entry.Key == "runID") { }
                //    else if (entry.Key == "testName") table += "<tr><td style='height:10px;'> Test Name</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                //    else if (entry.Key == "description") table += "<tr><td style='height:10px;'> Description</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                //    else if (entry.Key == "startTime") table += "<tr><td style='height:10px;'> Start Time</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                //    else if (entry.Key == "endTime") table += "<tr><td style='height:10px;'> End Time</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                //    else if (entry.Key == "runDuration")
                //    {
                //        int val = 0;
                //        try
                //        {
                //            val = int.Parse(entry.Value);
                //            val = val / 60;
                //        }
                //        catch { val = 0; }

                //        table += "<tr><td style='height:10px;'> Run Duration</td><td style='height:10px;' align='center'>" + val + " Minutes. </td></tr>";
                //    }
                //    else if (entry.Key == "WarmupTime")
                //    {
                //        int val = 0;
                //        try
                //        {
                //            val = int.Parse(entry.Value);
                //            val = val / 60;
                //        }
                //        catch { val = 0; }
                //        table += "<tr><td style='height:10px;'> Warmup Time</td><td style='height:10px;' align='center'>" + val + " Minutes. </td></tr>";
                //    }
                //    else if (entry.Key == "RunSettingUsed") table += "<tr><td style='height:10px;'> Run Setting Name</td><td style='height:10px;' align='center'>" + entry.Value + " </td></tr>";
                //    else if (entry.Key == "outcome") table += "<tr><td style='height:10px;'> Outcome of the Test</td><td style='height:10px;' align='center'>" + entry.Value + " </td></tr>";
                //    else if (entry.Key == "CooldownTime")
                //    {
                //        int val = 0;
                //        try
                //        {
                //            val = int.Parse(entry.Value);
                //            val = val / 60;
                //        }
                //        catch { val = 0; }
                //        table += "<tr><td style='height:10px;'> Cooldown Time</td><td style='height:10px;' align='center'>" + val + " Minutes. </td></tr>";
                //    }
                //}
                table += "</table></p></p></div>";
                indexHtml += table;
                table = "";
                //append test run summary end
                indexHtml += "<br><br><br><br><br><br>";

                //try
                //{
                //    //append overal test results start
                //    indexHtml += "<p><font size='large'>3.2 Overall Test Results</font>";
                //    indexHtml += "<p><table width='100%' border='1'><tr><td style='height:10px;' width='50%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Test Result Information</font></td><td style='height:10px;' width='50%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Value</font></td></tr>";

                //    //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                //    for (int i = 0; i < TestParent.OverallResultsArrayList.Count; i++)
                //    {
                //        Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.OverallResultsArrayList[i];
                //        var entry = dict.ElementAt(0);
                //        table += "<tr><td style='height:10px;'> " + entry.Key + "</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                //    }
                //    indexHtml += table + "</table></p></p>";

                //    //append overal test results end
                //}
                //catch { }



                indexHtml += "<br><br><br><br><br><br>";

                //Append top 5 slow pages start
                //try
                //{
                //    table = "";

                //    indexHtml += "<p><font size='large'>3.3 Top 5 Slowest Pages</font>";
                //    indexHtml += "<p><table width='100%' border='1'><tr><td style='height:10px;' width='75%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Page Name</font></td><td style='height:10px;' width='25%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Response Time</font></td></tr>";

                //    //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                //    for (int i = 0; i < TestParent.Top5SlowestPages.Count; i++)
                //    {
                //        Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.Top5SlowestPages[i];
                //        var entry = dict.ElementAt(0);
                //        table += "<tr><td style='height:10px;'> " + entry.Key + "</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                //    }
                //    indexHtml += table + "</table></p></p>";
                //}
                //catch { }
                ////Append top 5 slow pages end


                indexHtml += "<br><br><br><br><br><br>";

                //Append Top 5 Slowest Tests start
                //try
                //{
                //    table = "";

                //    indexHtml += "<p><font size='large'>3.4 Top 5 Slowest Tests</font>";
                //    indexHtml += "<p><table width='100%' border='1'><tr><td style='height:10px;' width='75%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Test Name</font></td><td style='height:10px;' width='25%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Response Time</font></td></tr>";

                //    //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                //    for (int i = 0; i < TestParent.Top5SlowestTestsArrayList.Count; i++)
                //    {
                //        Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.Top5SlowestTestsArrayList[i];
                //        var entry = dict.ElementAt(0);
                //        table += "<tr><td style='height:10px;'> " + entry.Key + "</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                //    }
                //    indexHtml += table + "</table></p></p>";
                //}
                //catch { }
                //Append Top 5 Slowest Tests end

                indexHtml += "<br>";

                //Append Page Results start
                try
                {
                    table = "";

                    indexHtml += "<p><font size='large'>3.5 Page Results</font>";
                    indexHtml += "<p><table width='100%' border='1'><tr>";

                    //var reskeys = ((Dictionary<String, String>)TestParent.PageResultsArrayList[0]).Keys;


                    //for (int i = 1; i < reskeys.Count; i++)
                    //{
                    //    indexHtml += "<td style='height:10px;' bgcolor='#9999FF' align='center'><font size='small' color='white'>" + reskeys.ElementAt(i) + "</font></td>";
                    //}

                    indexHtml += "</tr>";

                    //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                    //for (int i = 0; i < TestParent.PageResultsArrayList.Count; i++)
                    //{
                    //    Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.PageResultsArrayList[i];
                    //    var values = dict.Values;
                    //    indexHtml += "<tr>";
                    //    for (int ii = 1; ii < values.Count; ii++)
                    //    {
                    //        string DVal = "";

                    //        try
                    //        {
                    //            DVal = Math.Round(decimal.Parse(values.ElementAt(ii)), 2).ToString();
                    //        }
                    //        catch
                    //        {
                    //            DVal = values.ElementAt(ii);
                    //        }

                    //        indexHtml += "<td style='height:10px;' align='left'><font size='x-small' color='black'>" + DVal + "</font></td>";
                    //    }
                    //    indexHtml += "</tr>";
                    //}
                    indexHtml += table + "</table></p></p>";
                }
                catch { }
                //Append Page Results end

                //Append Graphs start

                string[] graphsArr = Directory.GetFiles(".\\..\\..\\Templates\\Images\\Graphs", "*.bmp");

                for (int g = 0; g < graphsArr.Length; g++)
                {
                    graphsArr[g] = graphsArr[g].Replace("\\", "/");
                }

                ArrayList graphs = new ArrayList(graphsArr);
                String cpuGraphPath = "";

                String ramGraphPath = "";

                for (int g = 0; g < graphs.Count; g++)
                {
                    if (graphs[g].ToString().EndsWith("-Processor-Time.jpg"))
                    {
                        cpuGraphPath = (graphs[g].ToString()).Replace("C:/Templates", "");
                        graphs.Remove(graphs[g]);
                    }
                }

                for (int g = 0; g < graphs.Count; g++)
                {
                    if (graphs[g].ToString().EndsWith("Available-MBytes.jpg"))
                    {
                        ramGraphPath = (graphs[g].ToString()).Replace("C:/Templates", "");
                        graphs.Remove(graphs[g]);
                    }
                }

                if (cpuGraphPath != "" || ramGraphPath != "")
                {
                    indexHtml += "<br><br><p><font size=\"large\">4. Primary Usage Graphs</font><table>";
                }

                if (cpuGraphPath != "")
                {
                    indexHtml += "<tr><td><font size='medium'>4.1 CPU Usage</font><img src=\"." + cpuGraphPath + "\" height=\"200\" width=\"600\" alt='Image'></img></td></tr>";
                }
                if (ramGraphPath != "")
                {
                    indexHtml += "<tr><td><font size='medium'>4.2 RAM Usage</font><img src=\"." + ramGraphPath + "\" height=\"200\" width=\"600\" alt='Image'></img></td></tr>";
                }

                if (cpuGraphPath != "" || ramGraphPath != "")
                {
                    indexHtml += "</table></p>";
                }

                //if (graphs.Count > 0) indexHtml += "<br><br><br><br><p><font size=\"large\">5. Other Counters Graphs</font><table>";

                //Random _rr = new Random();
                //int nn = _rr.Next(8, 9);

                //for (int gr = 1; gr < 11; gr++)
                //{
                //    String graphFileName = (graphs[gr].ToString()).Replace("C:/Templates", "");
                //    String graphName = Regex.Replace(graphFileName, "[^0-9a-zA-Z]+", " ");

                //    graphName = graphName.Replace("Images Graphs", "");
                //    graphName = graphName.Replace("jpg", "");

                //    indexHtml += "<tr><td><font size='medium'>5." + (gr + 1) + " " + graphName + "</font><img src=\"." + graphFileName + "\" height=\"200\" width=\"600\" alt='Image'></img></td></tr>";
                //}
                ////Append Graphs end
                //if (graphs.Count > 0) indexHtml += "</table></p>";
                indexHtml += "</body></html>";

                String rootPath = ".\\..\\..\\Templates\\";

                if (!Directory.Exists(rootPath))
                {
                    Directory.CreateDirectory(rootPath);
                    Directory.CreateDirectory(rootPath + "//Images");
                }

                //File.WriteAllText(rootPath + "index.html", indexHtml);          

                // HTML to DOCX conversion                

                Thread.Sleep(300);
                String filename = destination+"\\" + Guid.NewGuid().ToString() + ".docx";
                try
                {
                    using (WebClient client = new WebClient())
                    {
                    client.Headers["User-Agent"] =
                    "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                    "(compatible; MSIE 6.0; Windows NT 5.1; " +
                    ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                    // Download data.
                    string html = client.DownloadString("http://localhost:5050/index.html");
                    // Write values.

                    String imageHtml = "<table>";

                    Random _rr = new Random();
                    int nn = _rr.Next(8, 9);

                    for (int gr = 1; gr < 11; gr++)
                    {
                        String graphFileName = (graphs[gr].ToString()).Replace("./../../Templates", "");
                        //./../../Templates/Images/Graphs/-Privileged-Time.bmp
                        String graphName = Regex.Replace(graphFileName, "[^0-9a-zA-Z]+", " ");

                        graphName = graphName.Replace("Images Graphs", "");
                        graphName = graphName.Replace("jpg", "");

                        imageHtml += "<tr><td><font size='medium'>5." + (gr + 1) + " " + graphName + "</font><img src=\"." + graphFileName + "\" height=\"200\" width=\"600\" alt='Image'></img></td></tr>";
                    }
                    //Append Graphs end
                    if (graphs.Count > 0) imageHtml += "</table>";

                    html = html.Replace("imgHolder", imageHtml);

                    using (MemoryStream generatedDocument = new MemoryStream())
                    {
                        using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                        {
                            MainDocumentPart mainPart = package.MainDocumentPart;
                            if (mainPart == null)
                            {
                                mainPart = package.AddMainDocumentPart();
                                new Document(new Body()).Save(mainPart);
                            }
                            HtmlConverter converter = new HtmlConverter(mainPart);
                            converter.BaseImageUrl = new Uri("http://localhost:5050");
                            Body body = mainPart.Document.Body;

                            var paragraphs = converter.Parse(html);
                            for (int j = 0; j < paragraphs.Count; j++)
                            {
                                body.Append(paragraphs[j]);
                            }
                            mainPart.Document.Save();
                        }
                        File.WriteAllBytes(filename, generatedDocument.ToArray());
                    }
                    }                    
                }
                catch { }
                double progress = (double)(i / (double)NoOfFiles) * (double)100;
                reportWorker.ReportProgress((int)progress);
            }
            MWS.StopListen();
        }

        private void generate_XLSX_Documents()
        {
            string[] filesArr = Directory.GetFiles(".\\..\\..\\Templates\\Images\\Graphs", "*.jpg");
            Random ran = new Random();
            for (int i = 1; i <= NoOfFiles; i++)
            {
                try
                {
                    using (SpreadsheetDocument s = SpreadsheetDocument.Create(destination + "\\" + Guid.NewGuid().ToString() + ".xlsx", SpreadsheetDocumentType.Workbook))
                    {
                        s.CompressionOption = System.IO.Packaging.CompressionOption.NotCompressed;
                        WorkbookPart workbookPart = s.AddWorkbookPart();
                        Sheets sheets = new Sheets();
                        Workbook workbook = new Workbook();
                        FileVersion fileVersion = new FileVersion { ApplicationName = "Microsoft Office Excel" };

                        for (int ii = 1; ii <= 3; ii++)
                        {
                            WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                            string relId = workbookPart.GetIdOfPart(worksheetPart);

                            Worksheet worksheet = new Worksheet();
                            SheetData sheetData = new SheetData();
                            DateTime date = new DateTime(2009, 1, 1);
                            int salesLastYear = 25185;
                            int salesThisYear = 25348;

                            int range = ran.Next(100, 1000);

                            for (UInt32 r = 1; r <= range; r++)
                            {
                                Row contentRow = CreateContentRow(r, date, salesLastYear, salesThisYear);
                                sheetData.AppendChild(contentRow);
                                date = date.AddDays(7);
                                salesLastYear += (int)(salesLastYear * 0.031);
                                salesThisYear += (int)(salesThisYear * 0.027);
                            }
                            worksheet.Append(sheetData);

                            worksheetPart.Worksheet = worksheet;

                            worksheetPart.Worksheet.Save();

                            Sheet sheet = new Sheet { Name = "Sheet" + ii, SheetId = (uint)ii, Id = relId };
                            sheets.Append(sheet);
                            Random rImageNum = new Random();
                            int imageNum = rImageNum.Next(0, filesArr.Length - 1);
                            InsertImage(worksheetPart.Worksheet, 0, 2286000, filesArr[imageNum]);
                        }
                        workbook.Append(fileVersion);
                        workbook.Append(sheets);
                        s.WorkbookPart.Workbook = workbook;
                        s.WorkbookPart.Workbook.Save();

                        s.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                }
                double progress = (double)(i / (double)NoOfFiles) * (double)100;
                reportWorker.ReportProgress((int)progress);
            }
        }
        private void generate_PPTX_Documents()
        {
            Random _R = new Random();
            string[] filesArr = Directory.GetFiles(".\\..\\..\\Templates\\Images\\Graphs", "*.jpg");

            for (int i = 1; i <= NoOfFiles; i++)
            {
                String destinationFile = destination + "\\" + Guid.NewGuid().ToString() + ".pptx";
                File.Copy(originalFile, destinationFile, true);
                int count = _R.Next(5,10);

                for (int j = 1; j <= count; j++)
                {
                    using (PresentationDocument prstDoc = PresentationDocument.Open(destinationFile, true))
                    {
                        prstDoc.CompressionOption = CompressionOption.NotCompressed;
                        Slide slide = prstDoc.PresentationPart.InsertSlide("Title and Content");
                        DocumentFormat.OpenXml.Presentation.Shape shape = slide.CommonSlideData.ShapeTree.Elements<DocumentFormat.OpenXml.Presentation.Shape>().FirstOrDefault(
                            sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Title Layout".ToLower()));
                        DocumentFormat.OpenXml.Presentation.Picture pic = slide.AddPicture(shape, filesArr[count-j]);
                        slide.CommonSlideData.ShapeTree.RemoveChild<DocumentFormat.OpenXml.Presentation.Shape>(shape);
                        slide.Save();
                        prstDoc.PresentationPart.Presentation.Save();
                    }                    
                }
                double progress = (double)(i / (double)NoOfFiles) * (double)100;
                reportWorker.ReportProgress((int)progress);
            }
        }
        private static Row CreateContentRow(UInt32 index, DateTime date, int salesLastYear, int salesThisYear)
        {
            Row r = new Row { RowIndex = index };
            Cell cell1 = CreateTextCell("A", index, date.ToString());
            Cell cell2 = CreateNumberCell("B", index, salesLastYear);
            Cell cell3 = CreateNumberCell("C", index, salesThisYear);
            r.Append(cell1);
            r.Append(cell2);
            r.Append(cell3);
            return r;
        }
        static SlidePart CloneSlidePart(PresentationPart presPart, SlidePart templateSlide)
        {
            //Create Blank Slide
            SlidePart slide = presPart.AddNewPart<SlidePart>();

            //Feed data from existing template slide
            slide.FeedData(templateSlide.GetStream());

            //Layout should be same as that of template slide
            slide.AddPart(templateSlide.SlideLayoutPart);

            //Create new slide Id to show in our deck of slides
            SlideId slideId = new SlideId();
            slideId.RelationshipId = presPart.GetIdOfPart(slide);
            slideId.Id = id;
            id++;

            //Add it to presentation part
            presPart.Presentation.SlideIdList.Append(slideId);

            return slide;
        }
        private static void InsertContent(SlidePart templateSlide, string newText)
        {
            swapPlaceholderText(templateSlide, "Click to edit Master title style", newText);
        }
        protected static void InsertImage(Worksheet ws, long x, long y, long? width, long? height, string sImagePath)
        {
            try
            {
                WorksheetPart wsp = ws.WorksheetPart;
                DrawingsPart dp;
                ImagePart imgp;
                WorksheetDrawing wsd;

                ImagePartType ipt;
                switch (sImagePath.Substring(sImagePath.LastIndexOf('.') + 1).ToLower())
                {
                    case "png":
                        ipt = ImagePartType.Png;
                        break;
                    case "jpg":
                        ipt = ImagePartType.Jpeg;
                        break;
                    case "jpeg":
                        ipt = ImagePartType.Jpeg;
                        break;
                    case "gif":
                        ipt = ImagePartType.Gif;
                        break;
                    case "bmp":
                        ipt = ImagePartType.Bmp;
                        break;
                    default:
                        return;
                }

                if (wsp.DrawingsPart == null)
                {
                    //----- no drawing part exists, add a new one

                    dp = wsp.AddNewPart<DrawingsPart>();
                    imgp = dp.AddImagePart(ipt, wsp.GetIdOfPart(dp));
                    wsd = new WorksheetDrawing();
                }
                else
                {
                    //----- use existing drawing part

                    dp = wsp.DrawingsPart;
                    imgp = dp.AddImagePart(ipt);
                    dp.CreateRelationshipToPart(imgp);
                    wsd = dp.WorksheetDrawing;
                }

                using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
                {
                    imgp.FeedData(fs);
                }

                int imageNumber = dp.ImageParts.Count<ImagePart>();
                if (imageNumber == 1)
                {
                    DocumentFormat.OpenXml.Spreadsheet.Drawing drawing = new DocumentFormat.OpenXml.Spreadsheet.Drawing();
                    drawing.Id = dp.GetIdOfPart(imgp);
                    ws.Append(drawing);
                }

                DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties nvdp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties();
                nvdp.Id = new UInt32Value((uint)(1024 + imageNumber));
                nvdp.Name = "Picture " + imageNumber.ToString();
                nvdp.Description = "";
                DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
                picLocks.NoChangeAspect = true;
                picLocks.NoChangeArrowheads = true;
                DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureDrawingProperties nvpdp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureDrawingProperties();
                nvpdp.PictureLocks = picLocks;
                DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureProperties nvpp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureProperties();
                nvpp.NonVisualDrawingProperties = nvdp;
                nvpp.NonVisualPictureDrawingProperties = nvpdp;

                DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
                stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

                DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill blipFill = new DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill();
                DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
                blip.Embed = dp.GetIdOfPart(imgp);
                blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
                blipFill.Blip = blip;
                blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
                blipFill.Append(stretch);

                DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
                DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
                offset.X = 0;
                offset.Y = 0;
                t2d.Offset = offset;
                Bitmap bm = new Bitmap(sImagePath);

                DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();

                if (width == null)
                    extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
                else
                    extents.Cx = width;

                if (height == null)
                    extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
                else
                    extents.Cy = height;

                bm.Dispose();
                t2d.Extents = extents;
                DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties sp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties();
                sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
                sp.Transform2D = t2d;
                DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
                prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
                prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
                sp.Append(prstGeom);
                sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

                DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
                picture.NonVisualPictureProperties = nvpp;
                picture.BlipFill = blipFill;
                picture.ShapeProperties = sp;

                DocumentFormat.OpenXml.Drawing.Spreadsheet.Position pos = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Position();
                pos.X = x;
                pos.Y = y;
                Extent ext = new Extent();
                ext.Cx = extents.Cx;
                ext.Cy = extents.Cy;
                AbsoluteAnchor anchor = new AbsoluteAnchor();
                anchor.Position = pos;
                anchor.Extent = ext;
                anchor.Append(picture);
                anchor.Append(new ClientData());
                wsd.Append(anchor);
                wsd.Save(dp);
            }
            catch (Exception ex)
            {
                throw ex; // or do something more interesting if you want
            }
        }

        protected static void InsertImage(Worksheet ws, long x, long y, string sImagePath)
        {
            InsertImage(ws, x, y, null, null, sImagePath);
        }
        static void swapPlaceholderText(SlidePart slide, string placeholder, string newText)
        {
            List<DocumentFormat.OpenXml.OpenXmlElement> textList =
                    slide.Slide.Descendants()
                    .Where(t => t.InnerText.Equals(placeholder))
                    .ToList();

            for (int i = 0; i < textList.Count; i++)
            {
                try
                {
                    //if((textList[i]).ToString().Contains("DocumentFormat.OpenXml.Drawing.Text"))
                    {
                        Drawing.Text t = (Drawing.Text)textList[i];
                        t.Text = newText;
                    }                    
                }
                catch { }
            }
        }
        private static Cell CreateTextCell(string header, UInt32 index, string text)
        {
            Cell c = new Cell { DataType = CellValues.InlineString, CellReference = header + index };
            InlineString istring = new InlineString();
            DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text { Text = text };
            istring.Append(t);
            c.Append(istring);
            return c;
        }
        private static Cell CreateNumberCell(string header, UInt32 index, int number)
        {
            Cell c = new Cell { CellReference = header + index };
            CellValue v = new CellValue { Text = number.ToString() };
            c.Append(v);
            return c;
        }
    }
}
